package org.bbs.demo.concern.api;


import org.bbs.demo.advice.BusinessException;
import org.bbs.demo.common.BBSConstants;
import org.bbs.demo.common.Result;
import org.bbs.demo.concern.dao.AddConcernDao;
import org.bbs.demo.concern.dto.ConcernDto;
import org.bbs.demo.user.dto.UserInfoDto;
import org.bbs.demo.user.model.User;
import org.bbs.demo.utils.jwtutil.JWTutil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/concern")
@Transactional //事务声明，表示该类的所有方法都是事务性的，即方法中的所有访问数据库操作构成了一个整体事务，具有原子性
public class AddConcernApi {
    @Autowired
    private AddConcernDao addconcerndao;

    @PostMapping("/add")
    public Result info(@RequestBody ConcernDto concerndto, @RequestHeader String Token) {
        try {
            String followId = JWTutil.getUserID(Token);
            concerndto.setFollow_id(followId);
            String userId = concerndto.getUser_id();

            if (addconcerndao.findUser(userId) == null || addconcerndao.findUser(followId) == null) {
                throw new BusinessException("无法找到该用户");
                //return Result.err(BBSConstants.CODE_ERR_BUSINESS, "无法找该用户");
            }

            if (userId.equals(followId)){
                throw new BusinessException("无法关注自己");
                //return  Result.err(BBSConstants.CODE_ERR_BUSINESS,"无法关注自己");
            }

            if (addconcerndao.findConcern(concerndto) != null) {
                addconcerndao.updateSpecial(concerndto);
                return Result.OK("更新成功");
            }

            addconcerndao.addConcern(concerndto);
            return Result.OK("添加成功");
        } catch (DuplicateKeyException err) {
            throw new BusinessException("添加失败");
            //return Result.err(BBSConstants.CODE_ERR_SYS, "添加失败");
        }
    }
}
